package kz.pompei.OneGwt.ifaces.util;

import java.util.Iterator;

public abstract class AbstractHandlerList<H> implements Iterable<H> {
  
  private class Node {
    Node next;
    Node prev;
    H h;
  }
  
  private Node last = null;
  
  public HandlerKiller append(H h) {
    final Node node = new Node();
    node.h = h;
    
    if (last == null) {
      last = node;
      node.next = node;
      node.prev = node;
    } else {
      node.next = last.next;
      node.prev = last;
      last.next = node;
      node.next.prev = node;
      last = node;
    }
    
    return new HandlerKiller() {
      @Override
      public void killHandler() {
        if (node == node.next) {
          last = null;
          node.next = null;
          node.prev = null;
          return;
        }
        {
          node.prev.next = node.next;
          node.next.prev = node.prev;
          if (last == node) {
            last = node.prev;
          }
          node.next = null;
          node.prev = null;
        }
      }
    };
  }
  
  @Override
  public Iterator<H> iterator() {
    return new Iterator<H>() {
      private Node nowToReturn = last;
      private boolean needStepToNext = true;
      
      @Override
      public boolean hasNext() {
        return nowToReturn != null;
      }
      
      @Override
      public H next() {
        if (nowToReturn == null) throw new IllegalStateException();
        
        if (needStepToNext) {
          nowToReturn = nowToReturn.next;
          needStepToNext = false;
        }
        
        H ret = nowToReturn.h;
        
        if (nowToReturn == last) {
          nowToReturn = null;
        } else {
          nowToReturn = nowToReturn.next;
        }
        
        return ret;
      }
      
      @Override
      public void remove() {
        throw new UnsupportedOperationException();
      }
    };
  }
}
